#include "ota_http.h"
size_t gettxt(void *ptr, size_t size, size_t nmemb, void *userdata)
{
    size_t toalsize = size * nmemb;
    memcpy(userdata, ptr, toalsize);
    ((char *)userdata)[toalsize] = '\0';
    return toalsize;
}

char *Ota_Http_GetVersionInfo(char *url)
{
    CURL *curl_handle;
    CURLcode res;
    // 初始化全局环境变量
    curl_global_init(CURL_GLOBAL_DEFAULT);
    // 创建句柄
    curl_handle = curl_easy_init();
    if (curl_handle == NULL)
    {
        // handle创建失败
        log_error("handle创建失败");
        return NULL;
    }
    // 设置地址
    curl_easy_setopt(curl_handle, CURLOPT_URL, url);
    // 设置回调函数
    curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, gettxt);
    // 将接收到的数据写入缓冲区中
    char *txt = malloc(1024);
    memset(txt, 0, 1024);
    curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, txt);
    // 执行请求
    res = curl_easy_perform(curl_handle);
    if (res != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
        curl_easy_cleanup(curl_handle);
        return NULL;
    }
    log_info("请求成功");
    curl_easy_cleanup(curl_handle);
    // curl_global_cleanup();
    return txt;
}

GateState_t Ota_Http_DownLoad(char *url, char *path)
{
    CURL *curl_handle;
    CURLcode res;
    
    // 初始化全局环境变量
    // curl_global_init(CURL_GLOBAL_DEFAULT);
    // 创建句柄
    curl_handle = curl_easy_init();
    if (curl_handle == NULL)
    {
        // handle创建失败
        log_error("handle创建失败");
         return GATE_ERROR;
    }
    // 设置地址
    curl_easy_setopt(curl_handle, CURLOPT_URL, url);
    // 设置回调函数
    curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, fwrite);
    FILE *fp = fopen(path, "wb");
    if (fp == NULL)
    {
        log_error("打开文件失败");
        return GATE_ERROR;
    }
    curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl_handle);
    if (res != CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
        curl_easy_cleanup(curl_handle);
        return GATE_ERROR;
    }
    curl_easy_cleanup(curl_handle);
    // curl_global_cleanup();
    fclose(fp);
    log_info("下载成功");
    return GATE_OK;
}